package com.century.sjt.window;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.EMChat.activity.ChatActivity;
import com.century.sjt.activity.Forget_pwdPayActivity;
import com.century.sjt.activity.Pay.MerchantActivity;
import com.century.sjt.entity.Merchant;
import com.century.sjt.util.Base64Utils;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.gridpasswordview.GridPasswordView;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;


public class SelectPicPopupWindow extends PopupWindow {

    private Context mContext;

    private GridPasswordView gpvCashPwd;
    private String ComeNumber;
    private Button  btn_ok;
    private View mMenuView;
    private TextView forger_pwd;

    private RequestQueue mQueue;

    private String cashPwd="";
    private String webHost="";
    private PayPwdWindowListItemClickListener listener;
    public SelectPicPopupWindow(Activity context, final String MerchantId, final String discount, final String discountAmount,
                                final String orderAmount, final String mBlance,
                                final String Type,final String bankCardNo) {
        super(context);
        this.mContext= context;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.sjt_payok_item, null);
        mQueue = Volley.newRequestQueue(mMenuView.getContext());
        gpvCashPwd=(GridPasswordView) mMenuView.findViewById(R.id.pay_cashpwd);
        forger_pwd=(TextView) mMenuView.findViewById(R.id.sjt_forget_pwd);
        forger_pwd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("setpwd","3");
                intent.setClass(mContext, Forget_pwdPayActivity.class);
                mContext.startActivity(intent);
            }
        });

        btn_ok = (Button) mMenuView.findViewById(R.id.btn_payok);
        //确认按钮
        btn_ok.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                pay(gpvCashPwd.getPassWord(),MerchantId,discount,discountAmount,orderAmount,mBlance,Type,bankCardNo);
                //销毁弹出框
//                dismiss();
            }
        });
        //设置按钮监听

        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.AnimBottom);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x00000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        InputMethodManager imm = ( InputMethodManager ) mMenuView.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE );

        imm.showSoftInput(mMenuView,InputMethodManager.SHOW_FORCED);
        //mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
                mMenuView.setOnTouchListener(new OnTouchListener() {

                    public boolean onTouch(View v, MotionEvent event) {

                        int height = mMenuView.findViewById(R.id.pop_layout).getTop();
                        int y=(int) event.getY();
                        if(event.getAction()==MotionEvent.ACTION_UP){
                            if(y<height){
                                InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                                imm.hideSoftInputFromWindow(gpvCashPwd.getWindowToken(),0);
                                dismiss();
                            }
                        }
                        return true;
            }
        });
        gpvCashPwd.setOnPasswordChangedListener(new GridPasswordView.OnPasswordChangedListener() {
            @Override
            public void onChanged(String psw) {

            }

            @Override
            public void onMaxLength(String psw) {

                pay(gpvCashPwd.getPassWord(),MerchantId,discount,discountAmount,orderAmount,mBlance,Type,bankCardNo);
                //                Toast.makeText(SetCashPasswordActivity.this, password, Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * 确认支付
     */
    private void pay(final String cashPwd,final String MerchantId, final String discount, final String discountAmount, final String orderAmount,String mBlance,final String type,final String bankCardNo) {
        byte[] encodePwd = cashPwd.getBytes();
        final String pwd = Base64Utils.encode(encodePwd);
//        Log.e("pay",orderAmount+"&"+MerchantId+"&"+discount+"&"+discountAmount);
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME,mContext.getResources().getString(R.string.error_please_waitting), mContext);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.ApplyConsume, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("确认支付接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功

                        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(gpvCashPwd.getWindowToken() , 0);
                        dismiss();
                        listener.onSuccess(true);
//                        if (null == aMerchant){
//
//                        }else {
//                            mContext.startActivity(new Intent(mContext, ChatActivity.class).putExtra("userId",aMerchant.getUserId()));
//
//                        }

                    } else {//失败
                        TipUtil.showToast(message, mContext, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(mContext.getResources().getString(R.string.error_service), mContext, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(mContext.getResources().getString(R.string.error_network), mContext, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId","");
                map.put("loginId", userId);
                map.put("payerId",userId);
                map.put("cashPwd", pwd);
                map.put("recieverId",MerchantId);
                map.put("orderAmount",orderAmount);
                map.put("discount",discount);
                map.put("discountAmount",discountAmount+"");
                if (type.equals("1")){
                    map.put("accountAmount","0");
                    map.put("cardAmount",discountAmount);
                    map.put("bankCardNo",bankCardNo);
                }else {
                    map.put("accountAmount",discountAmount+"");
                    map.put("cardAmount","0");
                }
                map.put("fee","0");
                map.put("payMethod", type);
//                0：普通  1：商品订单
                map.put("orderType","0");
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = mContext.getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        mQueue.add(stringRequest);

    }


    public void showAppayRes(final String res) {
        new AlertDialog.Builder(mContext)
                .setMessage(res)
                .setTitle("提示")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Intent intent = new Intent();
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.putExtra("payType", "2");
                        intent.setClass(mContext, MerchantActivity.class);
                        mContext.startActivity(intent);

                    }
                })
                .show();
    }

    public void setPayPwdWindowListItemClickListener(PayPwdWindowListItemClickListener listener) {
        this.listener = listener;
    }
    public interface PayPwdWindowListItemClickListener{
        /**
         * 支付方式事件监听
         * @param
         * @return
         */
        void onPassWord(String pwd);
        boolean onSuccess(boolean message);

    }
}
